package com.example.workmanager;

import androidx.annotation.RequiresApi;
import androidx.appcompat.app.AppCompatActivity;
import androidx.lifecycle.Observer;
import androidx.work.BackoffPolicy;
import androidx.work.Constraints;
import androidx.work.Data;
import androidx.work.NetworkType;
import androidx.work.OneTimeWorkRequest;
import androidx.work.WorkInfo;
import androidx.work.WorkManager;

import android.os.Build;
import android.os.Bundle;
import android.util.Log;
import android.view.View;

import com.example.workmanager.work.MyWork;

import java.time.Duration;
import java.util.Timer;
import java.util.TimerTask;
import java.util.concurrent.TimeUnit;

public class MainActivity extends AppCompatActivity {

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
    }

    //workManager多用于后台执行任务
    //即必须要完成的任务 但是并不一定要立即完成
    @RequiresApi(api = Build.VERSION_CODES.O)
    public void mAddWork(View view) {
        //触发条件
        Constraints constraints = new Constraints.Builder()
                //设置网络需求
                .setRequiredNetworkType(NetworkType.NOT_REQUIRED)
                .build();

        //设置传递的参数
        Data inputData = new Data.Builder()
                .putString("input_data", "Jack")
                .build();

        //配置任务
        //一次性执行任务
        OneTimeWorkRequest workRequest = new OneTimeWorkRequest.Builder(MyWork.class)
                //设置触发条件
                .setConstraints(constraints)
                //延迟执行 延迟5秒钟
                .setInitialDelay(5, TimeUnit.SECONDS)
                //指数退避策略
                //当请求失败时 会等待一段时间自动重新请求  以下参数的意思为 线性增长 2秒钟
                .setBackoffCriteria(BackoffPolicy.LINEAR, Duration.ofSeconds(2))
                //添加标签 用于找到该任务
                .addTag("workRequest")
                //参数传递 参数是一个data类型的 可以在worker中获取到该参数
                .setInputData(inputData)
                .build();

        //提交任务到workManager中
        WorkManager workManager = WorkManager.getInstance(this);
        workManager.enqueue(workRequest);

        //观察任务状态
        workManager.getWorkInfoByIdLiveData(workRequest.getId()).observe(this, new Observer<WorkInfo>() {
            @Override
            public void onChanged(WorkInfo workInfo) {
                Log.d("guaimiao", workInfo.toString());
                if (workInfo != null && workInfo.getState() == WorkInfo.State.SUCCEEDED) {
                    String data = workInfo.getOutputData().getString("output_Data");
                    Log.d("guaimiao", data);
                }
            }
        });

        //取消任务
        //任务需要五秒才能完成
        //两秒时就取消任务
        new Timer().schedule(new TimerTask() {
            @Override
            public void run() {
                //workManager.cancelWorkById(workRequest.getId());
            }
        }, 2000);
    }
}